library(ggplot2)
library(reshape2)

# Creating the data frame from the provided table
df <- data.frame(
  Party = c("Total", "Democrat", "D. Lean", "Republican", "R. Lean", "Other"),
  `$0` = c(28.8, 18.9, 23.5, 49.2, 46.1, 33.6) / 100,
  `$10` = c(19.6, 19.6, 21.9, 15.9, 22.4, 18.3) / 100,
  `$20` = c(13.5, 16.6, 13.8, 7.7, 9.5, 11.7) / 100,
  `$30` = c(6.7, 8.0, 7.5, 4.1, 4.0, 8.0) / 100,
  `$40` = c(4.3, 5.5, 3.3, 3.1, 2.9, 2.9) / 100,
  `$50` = c(13.8, 15.3, 17.2, 10.3, 7.6, 14.6) / 100,
  `$60` = c(2.1, 2.5, 2.3, 1.7, 1.0, 1.5) / 100,
  `$70` = c(2.3, 2.7, 1.6, 2.4, 1.5, 2.2) / 100,
  `$80` = c(1.6, 2.4, 0.9, 0.8, 0.6, 1.5) / 100,
  `$90` = c(0.5, 0.6, 0.5, 0.3, 0.6, 0.7) / 100,
  `$100` = c(6.7, 8.0, 7.6, 4.5, 4.0, 5.1) / 100,
  check.names = FALSE
)

df <- df[order(-df$`$0`),]
df$Party <- factor(df$Party, levels = df$Party)


# Melting the data for use with ggplot
data_long <- melt(df, id.vars = "Party", variable.name = "Donation Amount")
data_long$`Donation Amount` <- factor(data_long$`Donation Amount`, 
                                      levels = c("$100", "$90", "$80", "$70", "$60", "$50", "$40", "$30", "$20", "$10", "$0"))

# Custom colors
custom_colors <- c(`$0` = "red3", `$10` = "red", `$20` = "darkorange", `$30` = "orange", 
                   `$40` = "yellow", `$50` = "white", `$60` = "lightblue", `$70` = "lightskyblue",
                   `$80` = "dodgerblue", `$90` = "dodgerblue4", `$100` = "darkblue")

# Create the stacked bar plot
ggplot(data_long, aes(x = Party, y = value, fill = `Donation Amount`)) +
  geom_bar(stat = "identity", position = "stack", colour = "black") +
  geom_text(aes(label = sprintf("%1.0f", value * 100)), position = position_stack(vjust = 0.5), color = "black", size = 3) +
  scale_fill_manual(values = custom_colors, name = "Donation Amount") +
  scale_y_continuous(labels = scales::percent_format()) +
  coord_flip() +
  labs(y = "", x = "", 
       title = "Individual Donations to Charity Fighting Climate Change by Party") +
  theme_minimal() +
  theme(panel.grid.major.y = element_blank(),
        panel.grid.minor.y = element_blank(),
        panel.grid.major.x = element_line(colour = "gray"),
        legend.position = "bottom")

# Save the plot
ggsave("MessagingFigsR/donations_by_party.png", width = 10, height = 6, dpi = 300)
